//
//  SourceLoginViewController.m
//  Ridding
//
//  Created by zys on 12-6-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SourceLoginViewController.h"

@interface SourceLoginViewController ()

@end

@implementation SourceLoginViewController
@synthesize web;
@synthesize staticInfo;
@synthesize activityView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        staticInfo=[StaticInfo getSinglton];
        requestUtil=[RequestUtil getSinglton];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGSize size = CGSizeMake(320, 44);
    UIImage *image = [self OriginImage:[UIImage imageNamed:@"navbg.png"] scaleToSize:size];
    [self.navigationController.navigationBar setBackgroundImage:image
                                                  forBarMetrics:UIBarMetricsDefault];
    //设置导航栏按钮      
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];
    [customBarItem setBackgroundImage:[UIImage imageNamed:@"返回按钮1.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [customBarItem setBackgroundImage:[UIImage imageNamed:@"返回按钮2.png"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = customBarItem;

    NSString *OAuthUrl=[NSString stringWithFormat:@"%@/bind/mobilesinabind/",QIQUNARHOME];
    NSString *url = [[NSString alloc]initWithString:OAuthUrl];
    NSURLRequest *loginRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; 
    [self.web setDelegate:self];
    [self.web loadRequest:loginRequest];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait||interfaceOrientation ==UIInterfaceOrientationPortraitUpsideDown);
}

-(void)back {  
    // Tell the controller to go back
    [self.navigationController popViewControllerAnimated:YES];
}


-(UIImage*)OriginImage:(UIImage *)image   scaleToSize:(CGSize)size    
{    
    // 创建一个bitmap的context    
    // 并把它设置成为当前正在使用的context    
    UIGraphicsBeginImageContext(size);    
    
    // 绘制改变大小的图片    
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];    
    
    // 从当前context中创建一个改变大小后的图片    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();    
    
    // 使当前的context出堆栈    
    UIGraphicsEndImageContext();    
    
    // 返回新的改变大小后的图片    
    return scaledImage;    
} 

- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [super viewWillAppear:animated];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    web.delegate=nil;
    self.navigationController.navigationBarHidden = YES;
   	[super viewWillDisappear:animated];
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    if(!activityView){
        activityView=[[ActivityView alloc]init:@"加载中..." lat:self.view.frame.size.width/2 log:self.view.frame.size.height/2];
        [self.view addSubview:activityView];
    }
    [activityView setHidden:NO];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
       [activityView setHidden:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString  *queryStr=[[request URL] query];
    NSLog(@"queryStr:%@",queryStr);
    NSDictionary *dic = [[self explodeString:queryStr ToDictionaryInnerGlue:@"=" outterGlue:@"&"] copy];
    if ([dic objectForKey:@"userId"] != nil) {
        staticInfo.user.userId=[dic objectForKey:@"userId"];
        staticInfo.user.authToken=[dic objectForKey:@"authToken"];
        staticInfo.user.sourceType=1;//新浪微博
        
        NSDictionary *profileDic=[requestUtil getUserProfile];
        staticInfo.user.name = [profileDic objectForKey:@"nickname"];
        staticInfo.user.bavatorUrl = [profileDic objectForKey:@"bavatorurl"];
        staticInfo.user.savatorUrl = [profileDic objectForKey:@"savatorurl"];
        staticInfo.user.totalDistance = [[profileDic objectForKey:@"totalDistance"]stringValue];
        staticInfo.user.accessUserId=[profileDic objectForKey:@"sourceid"];
        staticInfo.user.accessToken=[profileDic objectForKey:@"accessToken"];
        staticInfo.user.nowRiddingCount=[[profileDic objectForKey:@"riddingCount"]intValue];
        
        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        [prefs setObject:staticInfo.user.userId forKey:@"userId"];
        [prefs setObject:staticInfo.user.authToken forKey:@"authToken"];
        [prefs setInteger:staticInfo.user.sourceType forKey:@"sourceType"];
        [prefs setObject:staticInfo.user.accessToken forKey:@"accessToken"];
        [prefs setObject:staticInfo.user.accessUserId forKey:@"accessUserId"];
        [prefs setInteger:staticInfo.user.nowRiddingCount forKey:@"riddingCount"];
        
        [SFHFKeychainUtils storeUsername:staticInfo.user.userId andPassword:staticInfo.user.authToken forServiceName:@"riddingapp" updateExisting:TRUE error:nil];
        staticInfo.logined=true;
        [[SinaApiRequestUtil getSinglton] friendShip:@"骑去哪儿网" accessUserId:riddingappuid];
        
        HomeViewController* homeViewController = [HomeViewController alloc];
        [self.navigationController pushViewController:homeViewController animated:YES];
        [activityView removeFromSuperview];
    }
    return  YES;
}

- (NSMutableDictionary *)explodeString:(NSString*)src ToDictionaryInnerGlue:(NSString *)innerGlue outterGlue:(NSString *)outterGlue {
    // Explode based on outter glue
    NSArray *firstExplode = [src componentsSeparatedByString:outterGlue];
    NSArray *secondExplode;
    
    // Explode based on inner glue
    NSInteger count = [firstExplode count];
    NSMutableDictionary *returnDictionary = [NSMutableDictionary dictionaryWithCapacity:count];
    for (NSInteger i = 0; i < count; i++) {
        secondExplode = [(NSString *)[firstExplode objectAtIndex:i] componentsSeparatedByString:innerGlue];
        if ([secondExplode count] == 2) {
            [returnDictionary setObject:[secondExplode objectAtIndex:1] forKey:[secondExplode objectAtIndex:0]];
        }
    }
    
    return returnDictionary;
}


@end
